import os
import sys

function_tools_dir = '\\'.join(os.path.dirname(os.path.abspath(__file__)).split('\\')[:-1])
if function_tools_dir not in sys.path:
    sys.path.append(function_tools_dir)

from function_tools.place import LiuyaoPlace, GuideComponent

# 导入Flask核心类
from flask import Flask, render_template, request, jsonify, send_from_directory

# from html import unescape
from urllib.parse import unquote

# from markupsafe import escape
app = Flask(__name__)


@app.route('/')
def mainpage():
    return render_template('homepage.html')


@app.route('/submit', methods=['POST'])
def submit_form():
    # data = request.get_json()
    # title = data.get('title')
    # coinNum = data.get('coinNum')
    # time = data.get('time')
    # yongshen = data.get('yongshen')
    # theme = data.get('theme')

    title = request.form.get('title')
    coinNum = request.form.get('coinNum')
    time = request.form.get('time')
    yongshen = request.form.get('yongshen')
    theme = request.form.get('theme')

    # 处理数据...
    print("Title:", title)
    print("Coin Numbers:", coinNum)
    print("Time:", time)
    print("yongshen:", yongshen)
    print("theme:", theme)

    from function_tools.place import LiuyaoPlace, GuideComponent

    time_dict, msg_dict = GuideComponent(title, coinNum, time)
    model = LiuyaoPlace(time_dict, msg_dict)
    gua_text = model.place(isHtml=True)
    # print(gua_text) # gua_text正常输出

    # 直接返回gua_text
    return jsonify({'text': gua_text})


@app.route('/place_result')
def place_result():
    # Assume 'text' is passed from some previous operation or form data
    # 从URL的查询参数中获取'text'
    text = unquote(request.args.get('text', ''))
    # 将获取到的'text'值传递给模板
    return render_template('place_result.html', text=text)


# @app.route('/favicon.ico')
# def favicon():
#     # return send_from_directory(os.path.join(app.root_path, 'static'), 'girls.ico',                               mimetype='image/vnd.microsoft.icon')
#     return send_from_directory('static', 'images/favicon.ico', mimetype='image/vnd.microsoft.icon')


@app.route('/result', methods=['POST'])
def result():
    if request.method == 'POST':
        title = request.form.get('title')
        coinsNumber_list = request.form.get('Number_list')
        time_string = request.form.get('Time_list')

        my_place = place()
        text1, text2, text3 = my_place.placeClicked(title, coinsNumber_list, time_string)

        search_keys = [text1, text2, text3]
        # result_values = [key + 'appendix' for key in search_keys]
        return render_template('result.html', values=search_keys)


if __name__ == '__main__':
    app.config['DEBUG'] = True
    app.run()
